package com.css.fxfzfxqh.modules.population.service;

import com.alibaba.fastjson.JSON;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.common.rest.model.bo.JcsjDataTypeBo;
import com.css.fxfzfxqh.common.rest.model.bo.JcsjDataViewBo;
import com.css.fxfzfxqh.common.rest.model.bo.JcsjVersionMetaInfoBo;
import com.css.fxfzfxqh.common.rest.model.bo.JcsjVersionPageBo;
import com.css.fxfzfxqh.common.rest.model.param.JcDataVersionPageParam;
import com.css.fxfzfxqh.common.rest.model.param.JcsjDataViewParam;
import com.css.fxfzfxqh.common.rest.model.vo.JcsjVersionPageVo;
import com.css.fxfzfxqh.constants.FxfzConstants;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.common.rest.model.param.JcsjVersionPageParam;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.css.fxfzfxqh.zcpt.sys.service.impl.SysAreaCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PopulationService {
    @Autowired
    private JcsjRestManager jcsjRestManager;
    public static final String RKSJ_CODE = "rksj";
    public static final String RKGRID_CODE = "rkglwgsj";
    @Autowired
    private SysAreaCacheService sysAreaCacheService;
    @javax.annotation.Resource
    RedisTemplate redisTemplate;
    @Autowired
    SysAreaService sysAreaService;


    /**
     * 查询版本列表
     *
     * @param param 查询参数
     * @return
     * @throws BizException
     */
    public JcsjVersionPageBo versionPage(JcsjVersionPageParam param) throws BizException, UnsupportedEncodingException {
        param.setTypeCode(RKGRID_CODE);
        JcsjVersionPageBo r = jcsjRestManager.versionPage(param);
        if (r.getCode() == 200) {
            //Map<String, String> areaIdCodeMap = (Map<String, String>) JSON.parse((String) redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaIdCodeMap"));
            for (JcsjVersionPageVo jcsjVersionPageVo : r.getData().getList()) {
                String id = "";
                if(StringUtils.isNotBlank(jcsjVersionPageVo.getDataRangeProvince())){
                    id+=(jcsjVersionPageVo.getDataRangeProvince()+",");
                }
                if(StringUtils.isNotBlank(jcsjVersionPageVo.getDataRangeCity())){
                    id+=(jcsjVersionPageVo.getDataRangeCity()+",");
                }
                if(StringUtils.isNotBlank(jcsjVersionPageVo.getDataRangeArea())){
                    id+=(jcsjVersionPageVo.getDataRangeArea()+",");
                }
                if(id.endsWith(",")){
                    id = id.substring(0,id.length()-1);
                }
                String province = "";
                String city = "";
                String area = "";
                if(StringUtils.isNotBlank(id)){
                    String areaName = sysAreaService.getAreaNameByAreaId(id);
                    if(StringUtils.isNotBlank(areaName)){
                        String[] split = areaName.split(",");
                        if(split.length==3){
                            area = split[2];
                            city = split[1];
                        }else if(split.length==2){
                            city = split[1];
                        }
                        province = split[0];
                    }
                }

                jcsjVersionPageVo.setProvinceName(province);
                jcsjVersionPageVo.setCityName(city);
                jcsjVersionPageVo.setAreaName(area);
//                jcsjVersionPageVo.setProvinceName(sysAreaCacheService.getAreaNameByAreaId(jcsjVersionPageVo.getDataRangeProvince()));
//                jcsjVersionPageVo.setCityName(sysAreaCacheService.getAreaNameByAreaId(jcsjVersionPageVo.getDataRangeCity()));
//                jcsjVersionPageVo.setAreaName(sysAreaCacheService.getAreaNameByAreaId(jcsjVersionPageVo.getDataRangeArea()));
//                String code = null;
//                if (areaIdCodeMap==null||areaIdCodeMap.size()<1) {
//                    if ("1".equals(jcsjVersionPageVo.getDataRangeCountry()+"")){
//                        code = sysAreaService.getDivisionCodeById(jcsjVersionPageVo.getDataRangeProvince());
//                    }else if ("2".equals(jcsjVersionPageVo.getDataRangeCountry()+"")){
//                        code = sysAreaService.getDivisionCodeById(jcsjVersionPageVo.getDataRangeCity());
//                    }else {
//                        code = sysAreaService.getDivisionCodeById(jcsjVersionPageVo.getDataRangeArea());
//                    }
//                }else {
//                    if ("1".equals(jcsjVersionPageVo.getDataRangeCountry()+"")){
//                        code = areaIdCodeMap.get(jcsjVersionPageVo.getDataRangeProvince());
//                    }else if ("2".equals(jcsjVersionPageVo.getDataRangeCountry()+"")){
//                        code = areaIdCodeMap.get(jcsjVersionPageVo.getDataRangeCity());
//                    }else {
//                        code = areaIdCodeMap.get(jcsjVersionPageVo.getDataRangeArea());
//                    }
//                }
//                String geom = jcsjRestManager.getGeomByCode(code,jcsjVersionPageVo.getDataRangeCountry()+"");
//                jcsjVersionPageVo.setGeomText(geom);
            }
        }
        return r;
    }


    /**
     * 查询元数据信息接口
     *
     * @param versionCode 版本号
     */
    public JcsjVersionMetaInfoBo getMetaDataByVersionCode(String versionCode) throws BizException {
        return jcsjRestManager.getMetaDataByVersionCode(versionCode);
    }

    /**
     * 查询数据视图接口
     *
     * @param param 查询参数
     * @return
     * @throws BizException
     */
    public JcsjDataViewBo queryDataView(JcsjDataViewParam param) throws BizException {
        return jcsjRestManager.queryDataView(param);
    }

    public void versionDataExport(List<String> idList, HttpServletResponse response) throws BizException, IOException {
        Resource resource = jcsjRestManager.versionDataExport(idList);
        try (InputStream is = resource.getInputStream(); ServletOutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + resource.getFilename());
            response.setContentType("application/octet-stream;charset=utf-8");
            int flag = 0;
            while ((flag = is.read()) != -1) {
                outputStream.write(flag);
            }
            outputStream.flush();
        }
    }

    public JcsjDataTypeBo getDictItemByDictCode(String code) throws BizException {
        return jcsjRestManager.getDictItemByDictCode(code);
    }

    public void exportDataView(JcDataVersionPageParam param, HttpServletResponse response) throws IOException, BizException {
        Resource resource = jcsjRestManager.exportDataView(param);
        try (InputStream is = resource.getInputStream(); ServletOutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + resource.getFilename());
            response.setContentType("application/octet-stream;charset=utf-8");
            int flag = 0;
            while ((flag = is.read()) != -1) {
                outputStream.write(flag);
            }
            outputStream.flush();
        }
    }
}
